var enterpriseRecordCtrl = new XFApp.client();
Array.prototype.remove=function(dx)
{
	if(isNaN(dx)||dx>this.length){return false;}
	for(var i=0,n=0;i<this.length;i++)
	{
		if(this[i]!=this[dx])
		{
			this[n++]=this[i]
		}
	}
	this.length-=1
}
XFApp.client.prototype.iqEnterpriseRecord = {
	logi: function(msg){
		console.log(msg);
	},
	enterprisePage: '',
	shopPage: '',
	histroyPage: '',
	editId: '',
	attachArr: new Array(),
	attachType: '',
	attachCode: '',
	enterpriseList: '',
	successCode : "10000",
	loadingDialog: {},
	//网店信息数组
	shops: new Array(),
	urlItems : {
		submitEnterpriseRecordURL: basePath + '/userCenter/iqEnterprise/save',//提交企业备案
		saveEnterpriseRecordURL: basePath + '/userCenter/iqEnterprise/save',//暂存企业备案
		queryEnterprisePageURL: basePath + '/userCenter/iqEnterprise/selectPage',//查询企业列表数据
		submitToHGURL: basePath + '/userCenter/iqEnterprise/submit',//提交到通关平台
		queryEnterDetailURL: basePath + '/userCenter/iqEnterprise/selectDetail',//查询企业详情
		uploadUrl: basePath + '/userCenter/iqEnterpriseAttach/saveAttach',//上传企业附件
		deleteAttachUrl: basePath + '/userCenter/iqEnterpriseAttach/deleteAttach',//删除企业附件
		getAttachByEnterUrl: basePath + '/userCenter/iqEnterpriseAttach/selectAttach'
	},
	initView: function(){
		var _this = this;
		_this.initUploadPlugin();
		_this.queryEnterprisePage();
		_this.enterFormValidate();
		//_this.initCostumerCodeSelect();
	},
	initCostumerCodeSelect: function(){
		$("#COUNTRY_REGION_SELECT").bsSuggest({
			idField: "dictCode",
			keyField: "dictName",
			effectiveFields :["dictCode","dictName"],
			effectiveFieldsAlias:{dictCode:"编码",dictName:"名称"},
			data: {
				'value':customerCodes,
			}
		}).on('onSetSelectValue', function (e, keyword) {
			$("#COUNTRY_REGION").val(keyword.id);
		});
		customscodeUtil.setDefaultCustom("COUNTRY_REGION_SELECT",pspName);
	},
	//加载企业列表
	queryEnterprisePage: function(){
		_this = this;
		var params = {};
		if(!!_this.enterprisePage){
			_this.enterprisePage.page("remote",0,params);
		}else{
			_this.enterprisePage = $("#enterprisePage").page({
				pageSize : 5,
				remote: {
					url: _this.urlItems.queryEnterprisePageURL,
					params: {},
					success: function (data, pageIndex) {
						if(data.code==_this.successCode){
							var pageResult = data.result;
							_this.enterpriseList = pageResult.itemList;
							$("#enterpriseGrid").html($("#enterpriseDataTmpl").render(pageResult.itemList));
						}else{
							window.webDialogUtil.alert("提示",data.msg);
						}
					},
					error : function(){
						window.webDialogUtil.alert("提示",data.msg);
					}
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页'
			});
		}
	},
	submitEnterprise: function(){
		var _this = this;
		/*if(!$("#enterpriseForm").validate().form()){
			return;
		}
		if(!_this.editId && _this.attachArr.length == 0){
			window.webDialogUtil.alert("提示","请上传企业附件");
			return;
		}
		//是否选择了企业类型或者服务类型
		var isChooseType = false;
		$("#enterpriseForm input[type='checkbox']").each(function(index,el){
			if(el.checked == true){
				isChooseType = true;
			}
		});
		if(!isChooseType){
			window.webDialogUtil.alert("提示","请选择企业类型或服务类型");
			return;
		}*/
		var BUSINESS_MODES = "";
		$("input:checkbox[name='BUSINESS_MODE']:checked").each(function() {
			BUSINESS_MODES += $(this).val() + ",";
		});
		var ENT_TYPES = "";
		$("input:checkbox[name='ENT_TYPE']:checked").each(function() {
			ENT_TYPES += $(this).val() + ",";
		});

		var enterpriseData = _this.getEnterpriseFormData();
		enterpriseData.ENT_TYPE=ENT_TYPES;
		enterpriseData.BUSINESS_MODE=BUSINESS_MODES;
		_this.doSubmitEnter(enterpriseData);
		_this.logi(JSON.stringify(enterpriseData));
	},
	//提交到通关平台
	submitToHG: function(id,type){
		var _this = this;
		_this.loadingDialog = webDialogUtil.loading('正在提交，请稍后...');
		$.ajax({
			type:"POST",
			url:_this.urlItems.submitToHGURL,
			dataType:"json",
			data:{id:id,modifymark:type},
			success:function(data){
				if (data.code == _this.successCode) {
					window.webDialogUtil.alert("提示","提交成功");
					_this.loadingDialog.close();
					_this.queryEnterprisePage();
				}else{
					window.webDialogUtil.alert("提示",data.msg);
					_this.loadingDialog.close();
				}
			},
			error: function(){

				window.webDialogUtil.alert("提示","操作失败");
				_this.loadingDialog.close();
			}
		});
	},
	doSubmitEnter: function(data){
		var _this = this;
		_this.loadingDialog = webDialogUtil.loading('正在暂存，请稍后...');
		//基于ajaxfileUpload.js实现
		data.id = _this.editId;
		var attachids = "";
		for(var i = 0; i < _this.attachArr.length ; i ++){
			attachids += _this.attachArr[i].id + ','
		}
		data.attachIds = attachids.substring(0,attachids.length-1);
		$.ajax({
			url : _this.urlItems.submitEnterpriseRecordURL,
			secureuri : false,
			data: data,
			dataType : 'json',
			success : function(data) {
				_this.loadingDialog.close();
				if (data.code == _this.successCode) {
					if(data.result.id && _this.shops.length > 0){
						_this.queryEnterprisePage();
						_this.submitShopData(data.result.id);
					}else{
						window.webDialogUtil.alert("提示","暂存成功");
						_this.queryEnterprisePage();
						//_this.refreshEnterForm();


					}

				} else {
					window.webDialogUtil.alert("提示",data.msg);

				}

			},
			error : function(data, status, e){
				window.webDialogUtil.alert("提示",data.msg);
				_this.loadingDialog.close();
			}
		});
	},
	/**
	 * 获取企业备案的表单数据
	 */
	getEnterpriseFormData: function(){
		var _this = this;
		var enterpriseData = $('#enterpriseForm').serialize();
		enterpriseData = decodeURIComponent(enterpriseData,true);
		enterpriseData = _this.strToObj(enterpriseData);
		$("#enterpriseForm input[type='checkbox']").each(function(index,obj){
			if(obj.checked){
				enterpriseData[obj.name] = 'Y';
			}else{
				enterpriseData[obj.name] = 'N';
			}
			//_this.logi(enterpriseData);
		});
		return enterpriseData;
	},
	/**
	 * 加载企业详情
	 */
	loadEnterpriseDetail: function(id){
		var _this = this;
		$("#enterpriseForm")[0].reset();
		$("#enterpriseForm input").each(function(index,el){
			$(el).removeAttr('disabled');
		});
		$("#comments").removeAttr('disabled');
		$.ajax({
			type:"POST",
			url:_this.urlItems.queryEnterDetailURL,
			dataType:"json",
			data:{id:id},
			success:function(data){
				console.log(data);
				if (data.code != _this.successCode) {
					window.webDialogUtil.alert("提示","操作失败");
					return;
				}

				var item = data.result;
				_this.editId = item.id;
				for(var key in item){

					if($('#'+key)[0] && item.hasOwnProperty(key)){

						if($('#'+key)[0].tagName == 'TEXTAREA'){
							$('#'+key).html(item[key]);
						}else{
							$('#'+key).attr('value',item[key]);
						}

					}
				}
				$("#enterpriseForm input[type='checkbox']").each(function(index,el){
					if(item[el.id] === 'Y'){
						el.checked = true
					}else if(item[el.id] === 'N'){
						el.checked = false
					}
				});
				var businessMode = item.business_MODE;
				$("input:checkbox[name='BUSINESS_MODE']").each(function(index,el) {
					if(businessMode!=null && businessMode.indexOf($(this).val())>-1){
						el.checked=true;
					}else{
						el.checked=false;
					}
				});

				var entType = item.ent_TYPE;
				$("input:checkbox[name='ENT_TYPE']").each(function(index,el) {
					if(entType!=null && entType.indexOf($(this).val())>-1){
						el.checked=true;
					}else{
						el.checked=false;
					}
				});

				for(var i = 0; i < ENT_REG_PLACE_CODE_LIST.length; i ++){
					if(item.ent_REG_PLACE_CODE == ENT_REG_PLACE_CODE_LIST[i].dictCode){
						$("#ent_REG_PLACE_CODE_SELECT").val(ENT_REG_PLACE_CODE_LIST[i].dictName).attr("data-id",ENT_REG_PLACE_CODE_LIST[i].dictCode);
						$("#ent_REG_PLACE_CODE").val(ENT_REG_PLACE_CODE_LIST[i].dictCode);
					}
				}
				for(var i = 0; i < COUNTRY_REGION_LIST.length; i ++){
					if(item.country_REGION == COUNTRY_REGION_LIST[i].dictCode){
						$("#country_REGION_SELECT").val(COUNTRY_REGION_LIST[i].dictName).attr("data-id",COUNTRY_REGION_LIST[i].dictCode);
						$("#country_REGION").val(COUNTRY_REGION_LIST[i].dictCode);
					}
				}
				for(var i = 0; i < MONITOR_ORG_CODE_LIST.length; i ++){
					if(item.monitor_ORG_CODE == MONITOR_ORG_CODE_LIST[i].dictCode){
						$("#monitor_ORG_CODE_SELECT").val(MONITOR_ORG_CODE_LIST[i].dictName).attr("data-id",MONITOR_ORG_CODE_LIST[i].dictCode);
						$("#monitor_ORG_CODE").val(MONITOR_ORG_CODE_LIST[i].dictCode);
					}
				}
				for(var i = 0; i < COMPANY_SUBJECT_LIST.length; i ++){
					if(item.company_SUBJECT == COMPANY_SUBJECT_LIST[i].dictCode){
						$("#company_SUBJECT_SELECT").val(COMPANY_SUBJECT_LIST[i].dictName).attr("data-id",COMPANY_SUBJECT_LIST[i].dictCode);
						$("#company_SUBJECT").val(COMPANY_SUBJECT_LIST[i].dictCode);
					}
				}
				for(var i = 0; i < BUSINESS_TYPE_LIST.length; i ++){
					if(item.business_TYPE == BUSINESS_TYPE_LIST[i].dictCode){
						$("#business_TYPE_SELECT").val(BUSINESS_TYPE_LIST[i].dictName).attr("data-id",BUSINESS_TYPE_LIST[i].dictCode);
						$("#business_TYPE").val(BUSINESS_TYPE_LIST[i].dictCode);
					}
				}
				for(var i = 0; i < REGIST_OVERSEA_LIST.length; i ++){
					if(item.regist_OVERSEA == REGIST_OVERSEA_LIST[i].dictCode){
						$("#regist_OVERSEA_SELECT").val(REGIST_OVERSEA_LIST[i].dictName).attr("data-id",REGIST_OVERSEA_LIST[i].dictCode);
						$("#regist_OVERSEA").val(REGIST_OVERSEA_LIST[i].dictCode);
					}
				}
				_this.loadEnterpriseAttach(id);

				//_this.initUploadPlugin(item.picPath);
				//_this.queryShoplistByEnterprise(id);
			},
			error: function(){

				window.webDialogUtil.alert("提示","操作失败");
				_this.loadingDialog.close();
			}
		});
	},
	showEnterpriseDetail: function (id){
		var _this = this;
		_this.loadEnterpriseDetail(id);
		$("#enterpriseForm input").each(function(index,el){
			$(el).attr('disabled','disabled');
		});
		$("#comments").attr('disabled','disabled');
		_this.loadEnterpriseAttach(id);
	},
	/**
	 * 渲染文件上传框的样式
	 */
	initUploadPlugin: function (attch){
		var _this = this;
		var initialPreview = new Array();
		if(attch){
			initialPreview.push(remoteRes+attch);
			$("#fileinput").fileinput('refresh',{
				initialPreview: initialPreview
			});
		}
		$("#fileinput").fileinput({
			showUpload: false,
			maxFileCount: 1,
			language : 'zh',
			showCaption: false,
			mainClass: "input-group-lg",
			//allowedFileExtensions: ["jpg", "png", "gif"],
			initialPreviewAsData: false, // identify if you are sending preview data only and not the raw markup
			//showPreview:false,
			showRemove: false,
			showUpload: false,
			uploadUrl: _this.urlItems.uploadUrl
		}).on('fileselect',function(eve, numFiles, label){
			var files = $('#fileinput').fileinput('getFileStack');
			//验证文件类型
			var fileType = files[0].name.split('.');
			fileType = fileType[fileType.length-1];
			if(fileType != "png" && fileType != "jpg" && fileType != "gif"){
				$('#fileinput').fileinput('clear');
				window.webDialogUtil.toast({
					type: 'error',
					title: '请选择jpg，png，gif类型的文件'
				});
				return;
			};
			//验证文件大小
			var fileSize = files[0].size;
			if(fileSize>204800){
				$('#fileinput').fileinput('clear');
				window.webDialogUtil.toast({
					type: 'error',
					title: '附件大小不能超过200KB'
				});
				return;
			}
			/*$('#fileinput').fileinput('refresh',{
			 uploadExtraData : {
			 enterpriseId: _this.editId
			 }
			 });*/
			$(".file-preview").hide();
			if(_this.showFlag){
				$('#choose_attachtype_modal').modal();
			}

			//$('#fileinput').fileinput('upload');
		}).on('fileuploaded',function(event, data, previewId, index){
			if(data.response.isSuccess == true){
				_this.attachArr.push(data.response.result);
				window.webDialogUtil.toast({
					type: 'success',
					title: '上传成功'
				});
				_this.fileUploaded(_this.attachArr);
				_this.showFlag = true;
				_this.attachType = ''
				$("#attachMsgForm")[0].reset();
				//$('#attachCode').val('');
				//$("#attachtypeChoose").bsSuggest('destroy');
				//$("#attachtypeChoose").val('');
				//dictCtrl.dictionary.load("fileType","attachtype","attachtypeChoose");
			}else{
				window.webDialogUtil.toast({
					type: 'error',
					title: '上传失败'
				});
			}
		});
		$(".file-preview").hide();
	},
	//上传
	showFlag: true,
	doUpload: function(){
		/*if(!_this.attachType){
			window.webDialogUtil.toast({
				type: 'error',
				title: '请选择文件类型'
			});
			return ;
		}
		if(!$('#attachCode').val()){
			window.webDialogUtil.toast({
				type: 'error',
				title: '请输入文件号码'
			});
			return ;
		}*/
		$('#choose_attachtype_modal').modal('hide');
		$('#fileinput').fileinput('refresh',{
			uploadExtraData : {
				BIZ_TYPE_CODE: $('#BIZ_TYPE_CODE').val(),
				CERT_TYPE_CODE: $('#CERT_TYPE_CODE').val()
			}
		});
		_this.showFlag = false;
		$('#fileinput').fileinput('upload');
	},
	deleteAttach: function(id){
		$.ajax({
			type:"POST",
			url:_this.urlItems.deleteAttachUrl,
			dataType:"json",
			data:{id:id},
			success:function(data){
				if(data.isSuccess){
					for(var i = 0; i < _this.attachArr.length ; i ++){
						if(id && _this.attachArr[i].id == id){
							_this.attachArr.remove(i);
							$("#attachTableBody").html($("#attachDataTmpl").render(_this.attachArr));
							//_this.attachArr.remove(i);
						}
					}
				}else{
					window.webDialogUtil.toast({
						type: 'error',
						title: '删除失败'
					});
				}
			}
		});

	},
	fileUploaded: function(arr){
		if(arr.length > 0){
			for(var i = 0; i < arr.length ; i ++){
				var obj = arr[i];
				obj.picurl = remoteRes+obj.picturebit;

			}
			$("#attachTable").show();
			$("#attachTableBody").html($("#attachDataTmpl").render(arr));
		}
	},

	loadEnterpriseAttach: function(enterpriseId){
		$.ajax({
			type:"POST",
			url:_this.urlItems.getAttachByEnterUrl,
			dataType:"json",
			data:{id:enterpriseId},
			success:function(data){
				if(data.result.length>0){
					$("#attachTable").show();
					_this.fileUploaded(data.result);
					_this.attachArr = data.result;
				}
			}
		});
	},
	refreshUploadPlugin: function(){
		$('#fileinput').fileinput('clear');
	},
	enterFormValidate: function(){
		$("#enterpriseForm").validate(enterpriseValidate);
		$("#enterpriseForm").validate();
	},
	refreshEnterForm:function(){
		$('#filetd').children().remove();
		$('#filetd').append('<label class="control-label"></label><input id="fileinput" name="attach" type="file" multiple class="file-loading">');
		_this.initUploadPlugin();
		$("#enterpriseForm input[type='checkbox']").each(function(index,el){
			el.checked = false
		});
		$("#enterpriseForm input").each(function(index,el){
			//_this.logi(el.name);
			if(el.id=='fileinput'){
				//$('#fileinput').fileinput('clear');
			}else{
				el.value = '';
			}
		});
		$('#comments').html('');
		customscodeUtil.setDefaultCustom("customSelect",pspName);

	},
	/**
	 * 绑定页面事件
	 */
	event : function(){
		var _this = this;
		$('#showAddStoreDailog').on("click",function(){
			$('#choose_sku_modal').modal();
		});

		$('#saveEnterpriseBtn').on('click',function(){
			_this.submitEnterprise();
		});

		$('#saveShopBtn').on('click',function(){
			_this.saveShopFormData();
		})
		$("#attachtypeChoose").on('onSetSelectValue', function (e, keyword) {
			_this.attachType = keyword.key;
		})
		$("#btnUploadAttach").on('click',function(){
			_this.doUpload();
		});
	},

	strToObj: function(str){
		str = str.replace(/&/g,"','");
		str = str.replace(/=/g,"':'");
		str = "({'"+str +"'})";
		obj = eval(str);
		return obj;
	}

}

$(function(){
	dictCtrl.dictionary.load("ENT_TYPE",					"ent_TYPE",					"ent_TYPE_SELECT");//企业类别
	dictCtrl.dictionary.load("ENT_REG_PLACE_CODE",			"ent_REG_PLACE_CODE",		"ent_REG_PLACE_CODE_SELECT");//注册地代码
	dictCtrl.dictionary.load("COUNTRY_REGION",				"country_REGION",			"country_REGION_SELECT");//国家地区
	dictCtrl.dictionary.load("MONITOR_ORG_CODE",			"monitor_ORG_CODE",			"monitor_ORG_CODE_SELECT");//监管机构代码
	dictCtrl.dictionary.load("COMPANY_SUBJECT",				"company_SUBJECT",			"company_SUBJECT_SELECT");//备案主体
	dictCtrl.dictionary.load("BUSINESS_TYPE",				"business_TYPE",			"business_TYPE_SELECT");//进出口标志位
	dictCtrl.dictionary.load("REGIST_OVERSEA",				"regist_OVERSEA",			"regist_OVERSEA_SELECT");//境内外标志
	dictCtrl.dictionary.load("CERT_TYPE_CODE",				"CERT_TYPE_CODE",			"CERT_TYPE_CODE_SELECT");//企业附件单据类型
	dictCtrl.dictionary.load("BIZ_TYPE_CODE",				"BIZ_TYPE_CODE",			"BIZ_TYPE_CODE_SELECT");//附件业务类型
	enterpriseRecordCtrl.iqEnterpriseRecord.event();
	enterpriseRecordCtrl.iqEnterpriseRecord.initView();
	$('#expired').datetimepicker({
		format: 'yyyy-mm-dd',
		language:  'zh-TW',
		weekStart: 1,
		todayBtn:  1,
		autoclose: 1,
		todayHighlight: 1,
		startView: 2,
		minView: 2,
		forceParse: 0
	});
});